import {
  UpdateTeacherCourse,
  UpdateTeacherCourseMethods,
} from '@/pages/Admin/TeacherCourse/components/UpdateTeacherCourse';
import {
  deleteTeacherCourseUsingDelete,
  pageTeacherCourseUsingPost,
} from '@/services/student-management-system/jiaoshibanjishoukejiekou';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Popconfirm, Space, Table } from 'antd';
import { AddOutline } from 'antd-mobile-icons';
import React, { useEffect, useRef, useState } from 'react';

const TeacherCourse: React.FC = () => {
  const initSearchParam = {
    current: 1,
    pageSize: 5,
  };

  const [dataSource, setDataSource] = useState<API.TeacherCourseVO[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParam, setQueryParam] = useState<API.QueryTeacherCourseDTO>({
    ...initSearchParam,
  });
  const [title, setTitle] = useState<string>('');
  const [open, setOpen] = useState<boolean>(false);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [editTeacherCourse, setEditTeacherCourse] = useState<API.TeacherCourseVO>({});
  const [isEdit, setIsEdit] = useState(true);
  const childRef = useRef<UpdateTeacherCourseMethods>(null);

  /**
   * 点击编辑
   *
   * @param record
   */
  const handleOnEdit = (record: API.TeacherCourseVO) => {
    setTitle('编辑课程');
    setEditTeacherCourse({ ...record });
    setIsEdit(true);
    setOpen(true);
  };

  const handleOnDelete = async (record: API.TeacherCourseVO) => {
    const res = await deleteTeacherCourseUsingDelete({ ...record } as API.AddTeacherCourseDTO);
    if (res.code === 200) {
      message.success('删除成功');
      // 这里进行处理
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getTeacherCourses();
    } else {
      message.error('删除失败：' + res.msg);
    }
  };
  // 列元素
  const columns = [
    { title: '班级名称', dataIndex: 'className', key: 'className' },
    { title: '课程名称', dataIndex: 'courseName', key: 'courseName' },
    { title: '教师名称', dataIndex: 'teacherName', key: 'teacherName' },
    {
      title: '更多',
      dataIndex: 'options',
      width: '120px',
      render: (_: any, record: API.TeacherCourseVO) => (
        <Space>
          <Button size="small" variant="link" onClick={() => handleOnEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确认删除 ？"
            onConfirm={() => {
              handleOnDelete(record);
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 获取数据
  const getTeacherCourses = async () => {
    // FIXME 这里需要后端解决 模糊匹配问题
    console.log(queryParam);
    // 进行分页查找
    const res = await pageTeacherCourseUsingPost({ ...queryParam });
    if (res.code === 200) {
      message.success('获取数据成功');
      setDataSource(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  const handleSearch = (values: any) => {
    setQueryParam({ ...initSearchParam, ...values });
  };

  const handleOk = async () => {
    setConfirmLoading(true);
    try {
      const success = await childRef.current?.submitForm();
      if (success) {
        setOpen(false);
        getTeacherCourses();
      }
    } catch (error) {
      message.error('提交数据有误，请检查后再提交');
    } finally {
      setConfirmLoading(false); // 无论成功还是失败都应重置loading状态
    }
  };

  const handleCancel = () => setOpen(false);

  const handleAddClass = () => {
    setOpen(true);
    setTitle('新增');
    setIsEdit(false);
    setEditTeacherCourse({});
  };

  // 使用响应式
  useEffect(() => {
    getTeacherCourses();
  }, [queryParam]);

  return (
    <>
      <div className={'TeacherCourse'}>
        <Form layout="inline" onFinish={handleSearch}>
          <Form.Item name="courseName" label="课程名称">
            <Input style={{ width: 120 }} placeholder="请输入课程名称" />
          </Form.Item>
          <Form.Item name="className" label="班级名称">
            <Input style={{ width: 120 }} placeholder="请输入班级名称" />
          </Form.Item>
          <Form.Item name="teacherName" label="教师名称">
            <Input style={{ width: 120 }} placeholder="请输入教师名称" />
          </Form.Item>

          <Form.Item>
            <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>

        <Button
          icon={<AddOutline />}
          color="green"
          variant="solid"
          onClick={handleAddClass}
          style={{ marginTop: 10 }}
        >
          添加教师班级课程授课
        </Button>

        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={{
            total,
            current: queryParam.current,
            pageSize: queryParam.pageSize,
            onChange: (current, pageSize) => setQueryParam({ ...queryParam, current, pageSize }),
          }}
        />

        <Modal
          title={title}
          open={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <UpdateTeacherCourse
            isEdit={isEdit}
            editTeacherCourse={editTeacherCourse}
            onCloseModal={handleCancel}
            ref={childRef}
          />
        </Modal>
      </div>
    </>
  );
};

export default TeacherCourse;
